package org.zhadoop.stream.cql;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 命令行客户端参数处理类
 * @author zwd
 *
 */
@SuppressWarnings("static-access")
public class OptionProcessor {

	private static final Logger LOG = LoggerFactory.getLogger(OptionProcessor.class);
	
	private final Options options = new Options();
	private CQLSessionState ss;
	
	
	/**
	 * 构造函数
	 * @param sessionState
	 */
	public OptionProcessor(CQLSessionState sessionState) {
		this.ss = sessionState;
		initOptions();
	}

	/**
	 * 定义参数
	 */
	private void initOptions() {
		//-f <query-file>
		options.addOption(OptionBuilder.hasArg()
				.withLongOpt("file")
				.withArgName("filename")
				.withDescription("CQL from files")
				.create('f'));
		
		//[-s | -slient]
		options.addOption(new Option("s","slient",false,"Silent mode in interactive shell"));
		
		//[-H | -help]
		options.addOption(new Option("h", "help",false,"Print help information"));
	}
	
	public boolean parseAgr(String[] args){
		CommandLine commandLine = null;
		
		try {
			commandLine = new GnuParser().parse(options, args);
		} catch (ParseException e) {
			LOG.error("Command line option args error.");
			return false;
		}
		
		if(commandLine.hasOption('h')){
			printUsage();
			return false;
		}
		
		ss.setSlient(commandLine.hasOption('s'));
		ss.setFileName(commandLine.getOptionValue('f'));
		return true;
	}

	/**
	 * 打印帮助信息
	 */
	private void printUsage() {
		new HelpFormatter().printHelp("streaming", options);
	}

}
